package com.nulldev.util.JVM.reflections;

import java.util.Map;

import com.nulldev.util.VariableAPI.MathUtil.TimeUtil;
import com.nulldev.util.data.Arrays.maps.sem.SelfExpiringHashMap;

public class ClassCache {

	private static final Map<String, Class<?>> classCache = new SelfExpiringHashMap<String, Class<?>>(TimeUtil.fromMinutes(5), true);

	public static Class<?> forName(final String name) throws ClassNotFoundException {
		if (name == null || name.isEmpty())
			return null;
		else if (classCache.containsKey(name))
			return classCache.get(name);
		else {
			final Class<?> e = Class.forName(name);
			if (e == null)
				return e;
			classCache.put(name, e);
			return e;
		}
	}

	public static boolean hasCached(final String name) {
		if (name == null || name.isEmpty())
			return false;
		return classCache.containsKey(name);
	}

	public static boolean classExists(final String name) {
		if (name == null || name.isEmpty())
			return false;
		if (classCache.containsKey(name))
			return true;
		else {
			try {
				final Class<?> e = Class.forName(name);
				if (e == null)
					return false;
				classCache.put(name, e);
				return true;
			} catch (Exception e) {
				return false;
			}
		}
	}
}
